def readinp(fp):
    import GlobalParam
    gp=GlobalParam.iparam
    gi=GlobalParam.InputSpecifier()
    while True:
        eatline=fp.readline()
        neat=len(eatline.strip())
        if not eatline:
            break
        for i,if1 in enumerate(gi.if1gen()):
            f1=if1.match(eatline)
            if bool(f1):
                if i == 0:
                    # structure
                    gp.set_struct(f1.group(1))
                elif i == 1:
                    # lattice_param
                    gp.set_lattice_param(float(f1.group(1)))
                elif i == 2:
                    # ignore_layer
                    gp.set_ignore_layer(int(f1.group(1)))
                elif i == 3:
                    # source file form
                    gp.set_source_file(f1.group(1).strip())
                elif i == 4:
                    # xmakemol
                    gp.set_xmakemol(f1.group(1))
                elif i == 5:
                    # kmcfile
                    gp.set_kmcname(f1.group(1))
                elif i == 6:
                    # case
                    stripline=eatline.strip()
                    gp.set_case_string(stripline[4:neat])
                else:
                    pass
                break
            else:
                pass

def readsource():
    import GlobalParam
    import os
    import re
    gp=GlobalParam.iparam

    # Read source file
    fstr=re.sub(r"[*]",r"(\d+)",gp.file)
    fSRE=re.compile(fstr)
    clist=os.listdir('.')
    str1=[]
    str2=[]
    str3=[]
    for item1 in clist:
        f=fSRE.search(item1)
        if bool(f):
            str1.append(item1)
            str2.append(re.sub(r"[*]",f.group(1),gp.xmakemol))
            str3.append(re.sub(r"[*]",f.group(1),gp.kmcname))

    # Sort by number
    nrr1=[int(re.search(r"(\d+)",item).group(1)) for item in str1]
    arr1=zip(str1,nrr1)
    arr1.sort(key=lambda item:item[1])
    ar1,ar2=zip(*arr1)
    for item in ar2:
        gp.file_number_list.append(item)
    for item in ar1:
        gp.add_srcfile(item)

    nrr2=[int(re.search(r"(\d+)",item).group(1)) for item in str2]
    arr2=zip(str2,nrr2)
    arr2.sort(key=lambda item:item[1])
    ar1,ar2=zip(*arr2)
    for item in ar1:
        gp.add_xmlfile(item)

    nrr3=[int(re.search(r"(\d+)",item).group(1)) for item in str3]
    arr3=zip(str3,nrr3)
    arr3.sort(key=lambda item:item[1])
    ar1,ar2=zip(*arr3)
    for item in ar1:
        gp.add_kmcfile(item)

def sourceparam(fn):
    import GlobalParam
    gp=GlobalParam.iparam
    if gp.get_nsrcfile() == 0:
        print("No such files that have a form of %s\n" % gp.get_source_file())
        raise Exception
    fp=open(gp.get_srcfile(fn),'r')
    # Read time step
    eatline=fp.readline()
    eatline=fp.readline()
    # Read natom
    eatline=fp.readline()
    eatline=fp.readline()
    # Set number of atoms in source file and determine other parameters
    gp.set_natom(int(eatline))
    fp.close()


